package com.leetcode.queue;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Leetcode279 {

    public int numSquares(int n) {
        HashSet<Integer> squareNum = new HashSet<>();
        for (int i = 1; i * i <= n; i++) {
            squareNum.add(i*i);
        }
        Queue<Integer> queue = new LinkedList<>();
        HashSet<Integer> visited = new HashSet<>();
        queue.add(n);
        int level = 0;

        while (!queue.isEmpty()) {
            int len = queue.size();
            level++;
            for (int i = 0; i < len; i++) {
                int cur = queue.remove();
                for (Integer square : squareNum) {
                    int value = cur - square;
                    if (value < 0) {
                        continue;
                    }
                    if (!visited.contains(value)) {
                        if (value == 0) {
                            return level;
                        } else {
                            queue.add(value);
                            visited.add(value);
                        }
                    }
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(new Leetcode279().numSquares(18));
    }

}
